import { FC, useEffect } from 'react';
import styles from './index.module.scss';
import { Link, useNavigate } from 'react-router-dom';
import { Button, Checkbox, Form, Input, Space, Typography, message } from 'antd';
import { UserAddOutlined } from '@ant-design/icons';
import { REGISTER_PATHNAME, MANAGE_INDEX_PATHNAME } from '../../router';
import { useRequest } from 'ahooks';
import { loginService } from '../../services/user';
import { setUserToken } from '../../utils/user-token';
const { Title } = Typography;
const USERNAME_KEY = 'username';
const PASSWORD_KEY = 'password';
function rememberUser(username: string, password: string) {
  localStorage.setItem(USERNAME_KEY, username);
  localStorage.setItem(PASSWORD_KEY, password);
}

function forgetUser() {
  localStorage.removeItem(USERNAME_KEY);
  localStorage.removeItem(PASSWORD_KEY);
}

function getUser() {
  const username = localStorage.getItem(USERNAME_KEY);
  const password = localStorage.getItem(PASSWORD_KEY);
  return {
    username,
    password,
  };
}
type PropsTypes = {
  username: string;
  password: string;
  remember: boolean;
};
const Login: FC = () => {
  const nav = useNavigate();
  const { run: login, loading } = useRequest(
    async (values: PropsTypes) => {
      const { username, password } = values;
      const data = await loginService(username, password);
      return data;
    },
    {
      manual: true,
      onSuccess: (res) => {
        const { token = '' } = res;
        setUserToken(token);
        nav(MANAGE_INDEX_PATHNAME);
        message.success('登录成功');
      },
      onError: (err) => {
        message.error(err.message);
      },
    },
  );
  const onFinish = (values: PropsTypes) => {
    console.log('onFinish form content', values);
    if (values.remember) {
      rememberUser(values.username, values.password);
    } else {
      forgetUser();
    }
    login(values);
  };
  const [form] = Form.useForm();
  useEffect(() => {
    const { username, password } = getUser();
    form.setFieldsValue({ username, password });
  }, []);
  return (
    <div className={styles.container}>
      <div>
        <Space>
          <Title level={2}>
            <UserAddOutlined />
          </Title>
          <Title level={2}>用户登录</Title>
        </Space>
      </div>
      <div>
        <Form
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 16 }}
          onFinish={onFinish}
          initialValues={{ remember: true }}
          form={form}
        >
          <Form.Item
            label="用户名"
            name="username"
            rules={[
              {
                required: true,
                message: '请输入用户名',
              },
              {
                type: 'string',
                min: 5,
                max: 20,
                message: '字符长度在5-20之间',
              },
              {
                pattern: /^\w+$/,
                message: '只能是字母数字下划线',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="密码"
            name="password"
            rules={[
              {
                required: true,
                message: '请输入密码',
              },
            ]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 6, span: 16 }} name="remember" valuePropName="checked">
            <Checkbox>记住我</Checkbox>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 6, span: 16 }}>
            <Space>
              <Button htmlType="submit" type="primary" loading={loading}>
                登录
              </Button>
              <Link to={REGISTER_PATHNAME}>注册新用户</Link>
            </Space>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};
export default Login;
